//
//  WebProxy.m
//  fileUploadTest
//
//  Created by Erphan on 1/24/11.
//  Copyright 2011 Smonte. All rights reserved.
//

#import "WebProxy.h"
#import "RequestData.h"
#import "ASIHTTPRequest.h"

#define _APP_KEY @"bd670c9b0e3b167ea24c10315c6ace59"
#define _SECRET_KEY @"9980a8d46e72ee402424e55434aee861"

#define TWITTER_APPKEY @"ErXzq7J4otQVBpDcBGQQ"
#define TWITTER_SECRETKEY @"rLfYbNZIEq84NbInAkORBARN9UgctY7amno2vI744"


@interface WebProxy()
- (void) performRequestInBackground:(id) requestData;
- (BOOL) httpPostRequest:(NSString *) url :(NSDictionary *)headers :(NSString *)parameters :(NSMutableString *)responseBody :(RequestData *)requestData;
- (BOOL) httpGetRequest:(NSString *)url :(NSDictionary *)headers :(NSString *)parameters :(NSMutableString *)responseBody :(RequestData *)requestData;

@end


@implementation WebProxy


- (id)init {
    self = [super init];
	if(self)
	{
	}
	return self;
}

- (void)dealloc {
	[m_Delegate release];
	[super dealloc];
}

- (void) performHttpPostRequest:(RequestData *)request {
	[self performSelectorInBackground:@selector(performRequestInBackground:) withObject:request];
}

#pragma mark -
#pragma mark WebProxy Methods

- (void) performHttpPostRequest:(RequestData *)request :(id<WebProxyDelegate>) delegate {
	m_Delegate = delegate;
	[self performHttpPostRequest:request];
}

- (void) performRequestInBackground:(id)reqObject {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	RequestData *requestData = [(RequestData *)reqObject retain];
	
	//requestData.headers = [[NSMutableDictionary alloc] init];
	requestData.result = [[NSMutableString alloc] init];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	if (requestData.type == kPost) {
		requestData.completed = [self httpPostRequest:requestData.url :requestData.headers :requestData.parameters :requestData.result :requestData];
	} else {
		if (requestData.parameters == nil) {
			requestData.parameters = [NSString stringWithFormat:@""];
		}
		requestData.completed = [self httpGetRequest:requestData.url :requestData.headers :requestData.parameters :requestData.result :requestData];
	}
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	//NSLog(@"WEBPROXY -> URL: %@?%@", requestData.url, requestData.parameters);
	//NSLog(@"WEBPROXY -> BODY: %@", requestData.result);

	if([m_Delegate respondsToSelector:@selector(webProxyDidFinishRequest:)]) {
		[m_Delegate webProxyDidFinishRequest:requestData];
	} else {
		NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:requestData, @"RequestObject", nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:@"WebProxy" object:self userInfo:dict];
	}


	[requestData release];
	[pool release];
}

- (BOOL) httpPostRequest:(NSString *) url :(NSMutableDictionary *)headers :(NSString *)parameters :(NSMutableString *)responseBody :(RequestData *)reqData {
	
	if (url == nil || [url length] == 0) {
		return NO;
	}

	NSURL *requestURL = [NSURL URLWithString:url];
	
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setHTTPMethod:@"POST"];
	
	if (reqData.timeOut != 0) {
		[request setTimeoutInterval:reqData.timeOut];
	}

	if (!headers || ![headers objectForKey:@"content-type"]) {
		[request setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
	}
	
	if (headers) {
		for (NSString* key in headers) {
			[request setValue:[headers objectForKey:key] forHTTPHeaderField:key];
		}
	}
	
	[request setURL:requestURL];
	
	NSMutableData *requestData = [NSMutableData data];
	[requestData appendData:[parameters dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
	[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
	[request setHTTPBody:requestData];
	
	NSError *error = [[NSError alloc] init];
	
	NSHTTPURLResponse *responseCode = nil;
	
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request
												 returningResponse:&responseCode
															 error:&error];
	if (headers) {
		[headers setObject:[NSString stringWithFormat:@"%d", [responseCode statusCode]] forKey:@"StatusCode"];
	}
	NSHTTPURLResponse *httpResponse;
	httpResponse = (NSHTTPURLResponse *)responseCode;
	
	[headers addEntriesFromDictionary:[httpResponse allHeaderFields]];
	
	if ([responseCode statusCode] > 200) {
		reqData.completed = NO;
		return NO;
	}
	
	[responseBody appendString:[[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]autorelease]];
	reqData.completed = YES;
	return YES;
}

- (BOOL) httpGetRequest:(NSString *) url :(NSMutableDictionary *)headers :(NSString *)parameters :(NSMutableString *)responseBody :(RequestData *)reqData {
	
	if (url == nil || [url length] == 0) {
		return NO;
	}
	
	NSURL *requestURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", url, [parameters stringByAddingPercentEscapesUsingEncoding:NSWindowsCP1254StringEncoding]]];
	
	NSLog(@"%@", requestURL);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:requestURL];
    [request setValidatesSecureCertificate:NO];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        [request responseStatusCode];
        [responseBody appendString:[request responseString]];
        NSLog(@"Body: %@", responseBody);
        reqData.completed = YES;
        if (headers) {
            [headers setObject:[NSString stringWithFormat:@"%d", [request responseStatusCode]] forKey:@"StatusCode"];
            [headers addEntriesFromDictionary:[request responseHeaders]];
        }
        return YES;
    } else {
        return NO;
    }
	
//	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
//	
//	if (reqData.timeOut != 0) {
//		[request setTimeoutInterval:reqData.timeOut];
//	}
//	
//	[request setHTTPMethod:@"GET"];
//	
//	if (!headers || ![headers objectForKey:@"content-type"]) {
//		[request setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
//	}
//	
//	if (headers) {
//		for (NSString* key in headers) {
//			[request setValue:[headers objectForKey:key] forHTTPHeaderField:key];
//		}
//	}
//	
//	[request setURL:requestURL];
//		
//	NSError *error = [[NSError alloc] init];
//	
//	NSHTTPURLResponse *responseCode = nil;
//    
//	NSData *responseData = [NSURLConnection sendSynchronousRequest:request
//												 returningResponse:&responseCode
//															 error:&error];
//	NSHTTPURLResponse *httpResponse;
//	httpResponse = (NSHTTPURLResponse *)responseCode;
//
//	if (headers) {
//		//headers = [[NSMutableDictionary alloc] init];
//        [headers setObject:[NSString stringWithFormat:@"%d", [responseCode statusCode]] forKey:@"StatusCode"];
//        [headers addEntriesFromDictionary:[httpResponse allHeaderFields]];
//	}
//	
//	//NSLog(@"WebProxy: RequestCode (%d)", [responseCode statusCode]);
//
//	if ([responseCode statusCode] > 200) {
//		return NO;
//	}
//
//	[responseBody appendString:[[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]autorelease]];
//	reqData.completed = YES;
//	return YES;
}

#pragma mark -
#pragma mark NSURLConnectionDelegates

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        //if ([trustedHosts containsObject:challenge.protectionSpace.host])
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}


@end

/*
 //	NSString *urlStr = url;
 //    NSString *postBody = parameters;   
 //    NSMutableURLRequest *request;
 //    NSData *postData = [postBody dataUsingEncoding:NSASCIIStringEncoding];
 //    NSError *error;
 //    NSURLResponse *response;
 //    NSHTTPURLResponse *httpResponse;
 //    NSData *dataReply;
 //    id stringReply;
 //	
 //    request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:urlStr]];
 //	
 //    [request setHTTPMethod: @"POST"];
 //    [request setHTTPBody:postData];
 //    [request setValue:@"text/xml" forHTTPHeaderField:@"Accept"];
 //    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
 //	
 //    dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
 //    stringReply = (NSString *)[[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
 //    // Some debug code, etc.
 //    NSLog(@"reply from server: %@", stringReply);
 //    httpResponse = (NSHTTPURLResponse *)response;
 //    int statusCode = [httpResponse statusCode];  
 //    NSLog(@"HTTP Response Headers %@", [httpResponse allHeaderFields]); 
 //    NSLog(@"HTTP Status code: %d", statusCode);
 //    // End debug.
 */
